import type { FormProps } from 'antd'
import { Modal, Button, Checkbox, Form, Input } from 'antd'
import PropTypes from 'prop-types'
import { addUser, getUserOne, updateUser } from '@/api/user'

type FieldType = {
  username?: string
  password?: string
}
interface MyComponentProps {
  userData: {}
  addCallback: Function
  ModalCancel: Function
}

const AddUser: React.FC<MyComponentProps> = (props) => {
  // getUserOne({userId: detail.userId})
  console.log(props.userData)
  const [form] = Form.useForm()

  if (props.userData) {
    form.setFieldsValue(props.userData)
  }

  const submitUser = () => {
    form
      .validateFields()
      .then(async (values) => {
        if (Object.keys(props.userData).length === 0) {
          const add = await addUser(values)
          props.addCallback(add.data)
        } else {
          const update = await updateUser({ ...props.userData, ...values })
          props.addCallback(update.data)
        }
      })
      .catch((info) => {
        console.log('Failed:', info)
      })
  }

  return (
    <Modal
      title="用户"
      open
      onOk={submitUser}
      onCancel={() => props.ModalCancel()}
    >
      <Form form={form} name="basic">
        <Form.Item<FieldType>
          label="姓名"
          name="userName"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="邮箱"
          name="userEmail"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>

        {Object.keys(props.userData).length === 0 && (
          <Form.Item<FieldType>
            label="密码"
            name="userPwd"
            rules={[{ required: true }]}
          >
            <Input.Password />
          </Form.Item>
        )}

        <Form.Item<FieldType>
          label="呢称"
          name="nickname"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  )
}
AddUser.propTypes = {
  userData: PropTypes.object.isRequired,
  addCallback: PropTypes.func.isRequired,
  ModalCancel: PropTypes.func.isRequired
}
export default AddUser
